
/*
 * 获取组织单位store
 */
function getDepartStore(type){
	var store =  Ext.create('Ext.data.Store', {
		fields: ['corpdesc'],
		proxy: {
			type: 'ajax',
			url: basePath + "/workFlowdefAction/query/corpinfo",
			extraParams: {type: type},
			reader: {
				type: 'json',
				root: "corpInfos"
			} ,
			actionMethods: {
				create : 'POST',
				read   : 'POST', // by default GET
				update : 'POST',
				destroy: 'POST'
			}
		},
		pageSize: '50',
		autoLoad: false
	});
	return store;
}

/**
 * 获得界面的url或匹配规则的id
 */
function getPageUrlOrId(iframeId){
	var v_url="";
	
	var selectActivePanel=Ext.getCmp("modelConfigPanel");
	
	if(!selectActivePanel&&iframeId&&iframeId!=""){
		selectActivePanel=top.document.getElementById(iframeId).contentWindow.Ext.getCmp("modelConfigPanel");
	}
	
	if(selectActivePanel){
		var selection=selectActivePanel.navigationPanel.getSelectionModel();
		var aliasName=selection.getLastSelected().raw.aliasName;
		if(typeof(aliasName)!="undefined"&&aliasName){
			v_url+=aliasName;
			if(aliasName=="widget.specialityconfigform"){//如果为属性配置，需要定位到具体的panel id上
				var panel_left=Ext.getCmp("panel_left")||top.document.getElementById(iframeId).contentWindow.Ext.getCmp("panel_left")
				var items=panel_left.items.items;
				for(var i=0;i<items.length;i++ ){
					var compent=items[i];
					if(!compent.collapsed){
						v_url+="-"+compent.id;
						break;
					}
				}
			}
		}
	}else{
		var iframes=top.document.getElementsByTagName("iframe");
		v_url+="-"+iframes[iframes.length-1].src;
	}
	return v_url;
}


/**
 * 动态创建column表头过滤框
 */
function initSearch(gridId) {
	var columns = Ext.getCmp(gridId).columns;
	//var start = new Date().getTime();
	var onFlag = false;
	var flag = false;
	for(var i=0,len=columns.length;i<len;i++){
		var items = columns[i].items;
		if(items && items.length>0){
			var field = items.get(0);
			if(field){
				if(flag == false){
					onFlag = field.isHidden();
					flag = true;
				}
				if(!onFlag){
					field.setValue('');
				}
				field.setVisible(onFlag);
			}
		}
	}
	if(onFlag){
		Ext.getCmp(gridId+"_filter_button").setIconCls('icon-filter-on');
	}else{
		Ext.getCmp(gridId+"_filter_button").setIconCls('icon-filter-off');
		//快捷查询折叠时，清空查询条件
		var store = Ext.getCmp(gridId).getStore();
		var extraParams = store.getProxy().extraParams;
		extraParams['jsonString'] = '';
	}
	//var end = new Date().getTime();
	//alert("initSearch = " + (end - start) + " ms");
}

/**
 * 获得快捷查询的工具栏按钮
 * 
 * @param {}
 *            gridId gridid
 * @param {}
 *            obj 其他功能按钮
 */
function getColumnFilterTools(gridId,obj) {
	var toolBar = Ext.create('Ext.toolbar.Toolbar', {
		items : [{
					xtype : 'button',
					text : '快捷查询',
					id:gridId+'_filter_button',
					iconCls : 'icon-filter-off',
					handler : function() {
						initSearch(gridId);
					}
				}, {
					xtype : 'button',
					tooltip:"模糊查询",
					iconCls : 'icon-search',
					handler : function() {
						initGridDate(gridId);
					}
				}, {
					xtype : 'button',
					tooltip:"清除查询条件",
					iconCls : 'icon-search-clear',
					handler : function(){
						clearSearchContent(gridId);
					}
				}, '->']
	});

	if (obj) {
		for (var i in obj) {
			var button = obj[i];
			
			var v_id = (button.id == "" || button.id == "undefined")
					? "button_id_" + new Date().getTime()
					:gridId+"_"+button.id;
			var v_text = (typeof(button.text)=="undefined"||button.text == "" || button.text == "undefined")
					? "": button.text;
			var v_iconCls = (typeof(button.iconCls)=="undefined"||button.iconCls == "" || button.iconCls == "undefined")
					? "icon-add"
					: button.iconCls;
			
			switch(v_id){
				case gridId+"_add"://保存
					if(v_text==""){
						v_text = g_local.newadd;
					}	
					break;
				case gridId+"_save":
					if(v_text==""){
						v_text = g_local.save;
					}
					if(v_iconCls=="icon-add"){
						v_iconCls = "icon-save";
					}
					break;
				case gridId+"_delete":
					if(v_text==""){
						v_text = g_local.del;
					}
					if(v_iconCls=="icon-add"){
						v_iconCls = "icon-delete";
					}
					break;
				case gridId+"_submit":
					if(v_text==""){
						v_text = g_local.submit;
					}
					if(v_iconCls=="icon-add"){
						v_iconCls = "icon-submit";
					}
					break;
				case gridId+"_export":
					if(v_text==""){
						v_text = g_local.exportx;
					}
					if(v_iconCls=="icon-add"){
						v_iconCls = "icon-export";
					}
					break;
				case gridId+"_import":
					if(v_text==""){
						v_text = g_local.importx;
					}
					if(v_iconCls=="icon-add"){
						v_iconCls = "icon-import";
					}
					break;
			}
			button.id=v_id;
			button.text=v_text;
			button.iconCls=v_iconCls;
			
			var addButton = Ext.create('Ext.Button', button);
			toolBar.add(addButton);
		}
	}
	return toolBar;
}

/**
 * 根据类型 获得封装后的column item
 * 
 * @param {} gridId grid 的id(必填)
 * @param {} dataIndex 查询列的dataIndex(必填)
 * @param {} xtype 查询列的类型 textfield(默认):文本框;datefield:日期框;triggerfield:触发器;combobox:下拉框;
 * @param {} store 下拉框的store对象
 * @param {} onTriggerClick 触发器的点击后执行的方法
 */
function getFilterItem(gridId, dataIndex, xtype, store, onTriggerClick) {
	var items = [];
	if (typeof(xtype) == "undefined" || xtype == "") {
		var xtype = "textfield";
	} else {
		if (xtype == "combobox") {
			if (!store) {
				alert("xtype 为combobox时，必须设置store");
			}
		}
	}
	if (!dataIndex || dataIndex == "") {
		alert("getFilterItem 方法中的dataIndex必须设置参数");
		return;
	}
	var item = null;
	switch (xtype) {
		case "textfield" :// 文本框
			item =  new Ext.form.field.Text({
						name:dataIndex,
						flex : 1,
						margin : 2,
						enableKeyEvents : true,
						hidden : true,
						listeners : {
							keyup : function(a, e, eOpts) {
								if (this.value) {
									if (e.getKey() == Ext.EventObject.ENTER) {
										initGridDate(gridId);
									}
								}
							}
						}
					});
			break;
		case "readonlytextfield" :// 文本框
			/*item = new Ext.form.field.Text({
						name:dataIndex,
						disabled:true,
						hidden : true,
						flex : 1,
						margin : 2,
						enableKeyEvents : false
					});
					*/
			break;
		case "datefield" :// 日期框
			item = new Ext.form.field.Date({
				name:dataIndex,
			    flex : 1,
			    margin: 2,
			    format:'Y-m-d',
			    hidden : true,
			    enableKeyEvents: true,
			    listeners:{
		    	keyup: function( a, e, eOpts ) {
				        if (this.value) {
				        	if (e.getKey() == Ext.EventObject.ENTER) { 
				               initGridDate(gridId);
				            }
				        }
				    }
					}
				});
			break;
		case "triggerfield" :// 触发器
			item = new Ext.form.field.Trigger({
					name:dataIndex,
				    flex : 1,
				    margin: 2,
				    hidden : true,
				    enableKeyEvents: true,
				    triggerCls:'x-form-search-trigger',
				    onTriggerClick: function() {
				    	if(onTriggerClick){
				    		onTriggerClick();
				    	}else{
				    		alert('您还没有实现这个onTriggerClick')
				    	}
				    },
				    listeners:{
			    	keyup: function( a, e, eOpts ) {
					        if (this.value) {
					        	if (e.getKey() == Ext.EventObject.ENTER) {
					               initGridDate(gridId);
					            }
					        }
					    }
						}
					});
			break;
		case "combobox" :// 下拉框
			item = new Ext.form.field.ComboBox({
					name:dataIndex,
				    flex : 1,
				    margin: 2,
				    hidden : true,
					displayField:store.model.getFields()[0].name,//store取第一个字段的展示值
				    valueField:store.model.getFields()[1].name,//store取第二个字段的实际值
				    store:store,
				    enableKeyEvents: true,
				    listeners:{
			    	keyup: function( a, e, eOpts ) {
					        if (this.value) {
					        	if (e.getKey() == Ext.EventObject.ENTER) { 
					               initGridDate(gridId);
					            }
					        }
					    }
						}
					});
			break;
		case "s-combobox" :// 搜索下拉框
			item = new Ext.form.field.ComboBox({
					name:dataIndex,
				    flex : 1,
				    margin: 2,
				    hidden : true,
					displayField:store.model.getFields()[0].name,//store取第一个字段的展示值
				    valueField:store.model.getFields()[0].name,//store取第二个字段的实际值
				    store:store,
					queryParam: store.model.getFields()[0].name,
					minChars: 1,
				    enableKeyEvents: true,
				    listeners:{
			    	keyup: function( a, e, eOpts ) {
					        if (this.value) {
					        	if (e.getKey() == Ext.EventObject.ENTER) { 
					               initGridDate(gridId);
					            }
					        }
					    }
						}
					});
			break;
		case "" :
			item = new Ext.form.field.Text({
						name:dataIndex,
						flex : 1,
						margin : 2,
						hidden : true,
						enableKeyEvents : true,
						listeners : {
							keyup : function(a, e, eOpts) {
								if (this.value) {
									if (e.getKey() == Ext.EventObject.ENTER) {
										initGridDate(gridId);
									}
								}
							}
						}
					});
			break;
	}
	items.push(item);
	return items;
}

/**
 * 数据检索
 * 
 * @param {}
 *            gridId
 */
function initGridDate(gridId) {
	var curGrid = Ext.getCmp(gridId);
	if (!curGrid) {
		return;
	}
	var columns_num = curGrid.columns.length;
	var jsonStr = "{";
	for (var i = 0; i < columns_num; i++) {
		var items_num = curGrid.columns[i].items.length;
		if (items_num > 0) {

			var name = curGrid.columns[i].items.get(0).getName();
			var value = curGrid.columns[i].items.get(0).getValue();
			if (value != null && value != "") {
				if(value instanceof Date){
					value = Ext.util.Format.date(value,'Y-m-d');
				}
				jsonStr += name + ":" + "\"" + value + "\"" + ",";
			}
		}
	}
	if (jsonStr.lastIndexOf(",") != -1) {
		jsonStr = jsonStr.substring(0, jsonStr.lastIndexOf(","));
		//编码错误jsonStr=jsonStr+",quicksearch=1"导致快捷查询无效 修改于20171106
		jsonStr=jsonStr+",quicksearch:1"
	}
	jsonStr += "}";
	//jsonStr = "{cond:" + jsonStr + "}";
	//alert(jsonStr);
	
	var store = curGrid.getStore();
	//使模糊查询支持分页
	var extraParams = store.getProxy().extraParams;
	extraParams['jsonString'] = jsonStr;
	store.load({
				params : {
					start : 0,
					page  : 1,
					limit : 20
				}
			});
	curGrid.reconfigure();
}


/**
 * 清空快捷查询条件
 * @param {} gridId
 */
function clearSearchContent(gridId){
	var curGrid = Ext.getCmp(gridId);
	if (!curGrid) {
		return;
	}
	var columns_num = curGrid.columns.length;
	for (var i = 0; i < columns_num; i++) {
		var items_num = curGrid.columns[i].items.length;
		if (items_num > 0) {
			curGrid.columns[i].items.get(0).setValue('');
			//清除参数
			var store = curGrid.getStore();
			var extraParams = store.getProxy().extraParams;
			extraParams['jsonString'] = '';
		}
	}
}


//获取快捷查询通用的buttons
function getColumnFilterToolsItems(gridId){
	var buttons = [{
				xtype : 'button',
				text : '快捷查询',
				id:gridId+'_filter_button',
				iconCls : 'icon-filter-off',
				handler : function() {
					initSearch(gridId);
				}
			}, {
				xtype : 'button',
				tooltip:"模糊查询",
				iconCls : 'icon-search',
				handler : function() {
					initGridDate(gridId);
				}
			}, {
				xtype : 'button',
				tooltip:"清除查询条件",
				iconCls : 'icon-search-clear',
				handler : function(){
					clearSearchContent(gridId);
				}
			}];
	return buttons;
}

function clearIframe(id){
    var el = document.getElementById(id),
        iframe = el.contentWindow;
    if(el){
        el.src = 'about:blank';
        try{
            iframe.document.write('');
            iframe.document.clear();
        }catch(e){};
        //以上可以清除大部分的内存和文档节点记录数了
        //最后删除掉这个 iframe 就哦咧。
        document.body.removeChild(el);
    }
}